package com.xxx.landlord.Server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

public class WaitServer {
    private ServerSocket serverSocket;
    private List<ClientHandler> clients = new ArrayList<>();
    private int clientCount = 0;

    public WaitServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        System.out.println("Server started on port " + port);
    }

    public void start() {
        new Thread(() -> {
            try {
                while (true) {
                    Socket clientSocket = serverSocket.accept();
                    clientCount++;
                    String clientId = "U" + clientCount;
                    ClientHandler clientHandler = new ClientHandler(clientSocket, clientId);
                    clients.add(clientHandler);
                    new Thread(clientHandler).start();
                    clientHandler.send(clientId); // 发送客户端ID
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private class ClientHandler implements Runnable {
        private Socket socket;
        private BufferedReader in;
        private PrintWriter out;
        private String clientId;
        private boolean isReady = false;

        public ClientHandler(Socket socket, String clientId) throws IOException {
            this.socket = socket;
            this.clientId = clientId;
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
        }

        @Override
        public void run() {
            try {
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    // 处理客户端发送的消息
                    if (inputLine.startsWith("U") && inputLine.endsWith("!Ready")) {
                        isReady = true;
                        broadcast(clientId + "!Ready");
                    } else if (inputLine.startsWith("U") && inputLine.endsWith("!Unready")) {
                        isReady = false;
                        broadcast(clientId + "!Unready");
                    }
                    // 检查是否所有客户端都已就绪
                    checkAllReady();
                }
            }catch(SocketException e){
                System.out.println("Client " + clientId + " disconnected.");
                //客户端断开，将编号重新放入可用编号集合
                availableIds.add(clientId);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    socket.close();
                    clients.remove(this);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        public void send(String message) {
            out.println(message);
        }
    }

    //可用编号集合
    private List<String> availableIds = new ArrayList<>();
    {
        availableIds.add("U1");
        availableIds.add("U2");
        availableIds.add("U3");
    }

    private void broadcast(String message) {
        for (ClientHandler client : clients) {
            client.send(message);
        }
    }

    private void checkAllReady() {
        boolean allReady = true;
        for (ClientHandler client : clients) {
            if (!client.isReady) {
                allReady = false;
                break;
            }
        }
        if (allReady && !clients.isEmpty()) {
            // 所有客户端都已就绪，开始游戏
            broadcast("START3"); // 示例：倒数3秒开始
        }
    }

    public static void main(String[] args) {
        try {
            WaitServer server = new WaitServer(8080);
            server.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
